﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using AttTypeDefine;

public class Game1 : MonoBehaviour
{
    #region 成员变量及初始化信息
    Sprite m_sNormal;
    Sprite m_sPressed;
    protected Transform m_oPianoKey;
    protected RectTransform[] tran;
    public float m_fSphereSpeed = 200f;
    [Range(80,125)]
    public float m_fSphereBetween = 200f;
    public GameObject m_oMusicTab;
    GameObject m_oCountDown;
    GameObject NowSong; //当前Song
    GetSong getsong;
    public static bool isStart = false;  //当点击生成歌曲会让键盘和小球做匹配销毁
    bool m_bIsNotFirst = false;  //是否第一次生成歌曲，判断销毁之前list中小球
    public static bool isSong = false;//启动新song
    public static List<Transform> SphereList = new List<Transform>();
    string Name0; //小球的名字
    float isCanDead = -1.2f;
    string MusicScore;//曲谱  
    bool isFinal;
    bool m_bIsDown = false;
    public static Vector3[] m_vStartPos;//世界坐标x:-1.8，-0.8,0.2,1.2...y：-0.9
    private void Start()
    {
        m_oPianoKey = GlobalHelper.FindGameObjectWithName(gameObject, "Key").transform;//找到key，循环将key下打游戏对象（钢琴按键）加上监听时间
        int Count = m_oPianoKey.childCount;
        tran = new RectTransform[Count];
        m_vStartPos = new Vector3[Count];
        for (int i = 0; i < Count; i++)
        {
            tran[i] = m_oPianoKey.GetChild(i) as RectTransform;
            GameObject obj = tran[i].gameObject;
            EventTriggerListener.Get(obj).onEnter = Btn_Key;
            EventTriggerListener.Get(obj).onDown = OnDown;
            EventTriggerListener.Get(obj).onExit = OnExit;
            m_vStartPos[i] = new Vector3(tran[i].position.x, tran[i].position.y /*+ m_fButLen / 200*/, 0f);
        }
        m_oCountDown = Instantiate(Resources.Load("UI/CountDown")) as GameObject;//加入倒计时的预制体，并进行一些设置
        m_oCountDown.transform.SetParent(GlobalHelper.CANVAS.transform);
        m_oCountDown.transform.localScale = Vector3.one;
        m_oCountDown.SetActive(false);
        m_sNormal = Resources.Load("Image/Normal", typeof(Sprite)) as Sprite;
        m_sPressed = Resources.Load("Image/Pressed", typeof(Sprite)) as Sprite;
    }
    private void OnDown(GameObject obj)
    {
        m_bIsDown = true;
        Btn_Key(obj);
    }
    void OnExit(GameObject obj)
    {
        obj.GetComponent<Image>().sprite = m_sNormal;
    }
    private void Update()
    {
        if (Input.GetMouseButtonUp(0))
        {
            m_bIsDown = false;
        }
    }
    #endregion

    #region 点击钢琴键触发事件    
    private void Btn_Key(GameObject obj/*钢琴键*/)
    {
        if (m_bIsDown)
        {
            AudioMgr.PlayeAudio(obj, EAudioType.Audio_Keyboard, ((int)TurnTable.m_oNowGame).ToString() + "/" + obj.name);//通过琴键的名称和当前游戏的枚举值使键盘发出声音
            //换皮肤
            obj.GetComponent<Image>().sprite = m_sPressed;
            //在主要玩法中让小球失活
            if (isSong)
            {
                Name0 = SphereList[0].gameObject.name;
                if ((SphereList[0].position.y - (-1.2f)/*开始的y轴值*/) <= isCanDead)
                {
                    if (Name0 == obj.name)
                    {
                        StartCoroutine(SphereDead());
                    }
                }
            }
        }
    }
    #endregion

    #region 小球销毁
    IEnumerator SphereDead()
    {
        Transform t = SphereList[0];
        isStart = false;
        SphereTranslate sphere = t.gameObject.GetComponent<SphereTranslate>();
        sphere.m_bChange = false;
        isFinal = sphere.m_bFinal;
        if (1 == SphereList.Count && isSong&&!isFinal)
        {
            t.gameObject.GetComponent<Image>().color -= new Color(0, 0, 0, 1);
            yield return new WaitUntil(() => (1 < SphereList.Count));
            t.gameObject.GetComponent<Image>().color += new Color(0, 0, 0, 1);
        }
        SphereList.Remove(t);
        GlobalHelper.SpherePool.Despawn(t);
        SphereTranslateMgr.StartDrop();        
        isStart = true;
        if (isFinal)
        {
            isSong = false;
            AudioMgr.PlayeAudio(NowSong, AttTypeDefine.EAudioType.Audio_Finish, "Finish");
        }
    }
    #endregion

    #region 点击音乐触发事件
    public void ShowMusicTab()
    {
        m_oMusicTab.SetActive(true);
        GlobalHelper.IsTurn = false;
    }
    public void Btn_Music(GameObject obj)
    {
        m_oMusicTab.SetActive(false);
        GlobalHelper.IsTurn = true;
        isSong = false;
        SphereTranslateMgr.StartDrop();
        if (m_bIsNotFirst)
        {
            isStart = false;
            Destroy(NowSong);
            for (int i = 0; i < SphereList.Count; i++)
            {
                GlobalHelper.SpherePool.Despawn(SphereList[i]);
            }
            SphereList.Clear();
        }
        m_bIsNotFirst = true;
        int index = int.Parse(obj.name);
        SaveSong(ReaderInfo.Scorelist[index].score);      
    }
    public void SaveSong(string musicscore)
    {
        MusicScore = musicscore;
        NowSong = new GameObject("NewMusic");
        InstantiateCount(NowSong);
    }
    #endregion

    #region 倒计时
    void InstantiateCount(GameObject obj)
    {
        m_oCountDown.SetActive(true);
        AudioMgr.PlayeAudio(m_oCountDown, AttTypeDefine.EAudioType.Audio_CountDown, "CountDown");
        GlobalHelper.Event.SetActive(false);
        GlobalHelper.IsTurn = false;
        StartCoroutine(Waittime(obj));
    }
    IEnumerator Waittime(GameObject obj)
    {
        yield return new WaitUntil(() => isSong);
        isStart = true;
        // 主要玩法,引导弹琴
        // 加载相应的玩法（GetSong）并将键的初始位置传入
        getsong = obj.AddComponent<GetSong>();
        getsong.m_strSong = MusicScore;
        getsong.OnStart();
        GlobalHelper.Event.SetActive(true);
        GlobalHelper.IsTurn = true;
    }
    #endregion

    #region 
    void OnDisable()
    {
        if (m_bIsNotFirst)
        {
            Destroy(NowSong);
            for (int i = 0; i < Game1.SphereList.Count; i++)
            {
                GlobalHelper.SpherePool.Despawn(SphereList[i]);
            }
            SphereList.Clear();
        }
        isSong = false;
    }
    #endregion
}
